package com.yanzu.module.system.controller.admin.tenant;

import com.alibaba.fastjson.JSONObject;
import com.yanzu.framework.common.pojo.CommonResult;
import com.yanzu.framework.common.pojo.PageResult;
import com.yanzu.framework.datapermission.core.annotation.DataPermission;
import com.yanzu.framework.excel.core.util.ExcelUtils;
import com.yanzu.framework.operatelog.core.annotations.OperateLog;
import com.yanzu.framework.tenant.config.TenantProperties;
import com.yanzu.framework.tenant.core.aop.TenantIgnore;
import com.yanzu.module.system.controller.admin.tenant.vo.tenant.*;
import com.yanzu.module.system.convert.tenant.TenantConvert;
import com.yanzu.module.system.dal.dataobject.dict.DeviceNumDO;
import com.yanzu.module.system.dal.dataobject.dict.DictDataDO;
import com.yanzu.module.system.dal.dataobject.tenant.TenantDO;
import com.yanzu.module.system.service.dict.DictDataService;
import com.yanzu.module.system.service.tenant.TenantService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import static com.yanzu.framework.common.pojo.CommonResult.success;
import static com.yanzu.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static javafx.beans.binding.Bindings.when;

@Tag(name = "管理后台 - 租户")
@RestController
@RequestMapping("/system/tenant")
public class TenantController {

    @Resource
    private TenantService tenantService;

    @Resource
    private DictDataService dictDataService;

    @GetMapping("/get-id-by-name")
    @PermitAll
    @Operation(summary = "使用租户名，获得租户编号", description = "登录界面，根据用户的租户名，获得租户编号")
    @Parameter(name = "name", description = "租户名", required = true, example = "1024")
    public CommonResult<Long> getTenantIdByName(@RequestParam("name") String name) {
        TenantDO tenantDO = tenantService.getTenantByName(name);
        return success(tenantDO != null ? tenantDO.getId() : null);
    }

    @PostMapping("/create")
    @Operation(summary = "创建租户")
    @PreAuthorize("@ss.hasPermission('system:tenant:create')")
    public CommonResult<Long> createTenant(@Valid @RequestBody TenantCreateReqVO createReqVO) {
        return success(tenantService.createTenant(createReqVO));
    }

    @GetMapping("/getMeal")
    @Operation(summary = "获得租户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<JSONObject> getMeal(@RequestParam("id") Long id) {
        List<DeviceNumDO> deviceNumList = dictDataService.getDeviceNumList(id);
        JSONObject jsonObject = new JSONObject();
        deviceNumList.forEach(f->{
            Integer deviceNum = f.getDeviceNum();
            String deviceType = f.getDeviceType();
            jsonObject.put(deviceType, deviceNum);
        });
        jsonObject.put("id", id);
        return success(jsonObject);
    }



    @PostMapping("/setMeal")
    @Operation(summary = "配置设备")
    @PreAuthorize("@ss.hasPermission('system:tenant:create')")
    @TenantIgnore
    public CommonResult<Long> setMeal(@Valid @RequestBody JSONObject jsonObject) {
        //获取设备字典
        List<DictDataDO> memberDeviceType = dictDataService.getDictDataOneList("member_device_type");
        Long id = jsonObject.getLong("id");
        dictDataService.deleteDeviceNum(id);
        memberDeviceType.forEach(f->{
            String value = f.getValue();
            Integer integer = jsonObject.getInteger(value);
            DeviceNumDO deviceNumReqVO = new DeviceNumDO();
            deviceNumReqVO.setConfigurationId(id);
            deviceNumReqVO.setDeviceType(value);
            deviceNumReqVO.setDeviceNum(integer);
            dictDataService.createDeviceNum(deviceNumReqVO);

            //查询已添加设备数量
            int tenCount = dictDataService.getTenCount(id, Integer.valueOf(value));
            //开启数目
            Integer OnNum  = 0;
            //关闭数目
            Integer OffNum  = 0;
            if (tenCount >= 0 &&  integer >= 0 ) {
                //判断当限制数目大于已有设备数目
                if(integer>=tenCount){
                    OnNum = tenCount;
                }else {
                    OffNum = tenCount - integer;
                    OnNum = integer;
                }
            }
            //查询需要关闭的设备
            List<Long> desc = dictDataService.getDeviceId(OffNum, "DESC",id, Integer.valueOf(value));
            //查询需要开启的设备
            List<Long> asc = dictDataService.getDeviceId(OnNum, "ASC",id, Integer.valueOf(value));
            if (desc != null && desc.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (Long l : desc) {
                    if (sb.length() > 0) {
                        sb.append(",");
                    }
                    sb.append(l);
                }
                String str = sb.toString();
                dictDataService.updateEnable(1,str);
            }

            if (asc != null && asc.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (Long l : asc) {
                    if (sb.length() > 0) {
                        sb.append(",");
                    }
                    sb.append(l);
                }
                String str = sb.toString();
                dictDataService.updateEnable(0,str);
            }
        });
        return null;
    }



    @PutMapping("/update")
    @Operation(summary = "更新租户")
    @PreAuthorize("@ss.hasPermission('system:tenant:update')")
    public CommonResult<Boolean> updateTenant(@Valid @RequestBody TenantUpdateReqVO updateReqVO) {
        tenantService.updateTenant(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除租户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant:delete')")
    public CommonResult<Boolean> deleteTenant(@RequestParam("id") Long id) {
        tenantService.deleteTenant(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得租户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<TenantRespVO> getTenant(@RequestParam("id") Long id) {
        TenantDO tenant = tenantService.getTenant(id);
        return success(TenantConvert.INSTANCE.convert(tenant));
    }

    @GetMapping("/page")
    @Operation(summary = "获得租户分页")
    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<PageResult<TenantRespVO>> getTenantPage(@Valid TenantPageReqVO pageVO) {
        PageResult<TenantDO> pageResult = tenantService.getTenantPage(pageVO);
        return success(TenantConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出租户 Excel")
    @PreAuthorize("@ss.hasPermission('system:tenant:export')")
    @OperateLog(type = EXPORT)
    public void exportTenantExcel(@Valid TenantExportReqVO exportReqVO,
                                  HttpServletResponse response) throws IOException {
        List<TenantDO> list = tenantService.getTenantList(exportReqVO);
        // 导出 Excel
        List<TenantExcelVO> datas = TenantConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "租户.xls", "数据", TenantExcelVO.class, datas);
    }


}
